package com.zidian.leader.adapter;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.DefaultAxisValueFormatter;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.zidian.leader.R;
import com.zidian.leader.common.util.ColorConstants;
import com.zidian.leader.common.util.StringConstants;
import com.zidian.leader.entity.QuestionnaireDetail;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 问卷混合图表adapter
 * Created by GongCheng on 2016/11/9.
 */

public class QuestionnaireChartListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    //条形图
    private static final int TYPE_BAR_CHART = 1;
    //饼状图
    private static final int TYPE_PIE_CHART = 2;

    private List<QuestionnaireDetail> list;
    private Context context;
    private LayoutInflater inflater;

    public QuestionnaireChartListAdapter(Context context) {
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_BAR_CHART) {
            View view = inflater.inflate(R.layout.item_questionnaire_bar_chart, parent, false);
            return new BarChartViewHolder(view);
        } else if (viewType == TYPE_PIE_CHART) {
            View view = inflater.inflate(R.layout.item_questionnaire_pie_chart, parent, false);
            return new PieChartViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof BarChartViewHolder) {
            //设置标题
            ((BarChartViewHolder) holder).questionnaireTitleTv.setText((position + 1) + "." + list.get(position).getQuestionContent());
            initBarChart(((BarChartViewHolder) holder).questionnaireChartBc, position);
            ((BarChartViewHolder) holder).questionnaireChartBc.setData(getBarData(position));
            ((BarChartViewHolder) holder).questionnaireChartBc.invalidate();
            //设置问题选项描述
            ((BarChartViewHolder) holder).adapter.setData(getOptionDescribes(position));
        } else if (holder instanceof PieChartViewHolder) {
            ((PieChartViewHolder) holder).questionnaireTitleTv.setText((position + 1) + "." + list.get(position).getQuestionContent());
            initPieChart(((PieChartViewHolder) holder).questionnaireChartPc);
            ((PieChartViewHolder) holder).questionnaireChartPc.setData(getPieData(position));
            ((PieChartViewHolder) holder).questionnaireChartPc.invalidate();
            //设置问题选项描述
            ((PieChartViewHolder) holder).adapter.setData(getOptionDescribes(position));
        }
    }

    /**
     * 得到选项描述list
     *
     * @param position 位置
     * @return         描述List
     */
    private List<String> getOptionDescribes(int position) {
        List<String> describes = new ArrayList<>();
        for (int i = 0; i < list.get(position).getStatistical().size(); i++) {
            describes.add(list.get(position).getStatistical().get(i).getOptionsDescribe());
        }

        return describes;
    }

    public void setData(List<QuestionnaireDetail> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(int position) {
        if (list.get(position).getQuestionTypes().equals("打分题")) {
            return TYPE_BAR_CHART;
        } else if (list.get(position).getQuestionTypes().equals("选择题")) {
            return TYPE_PIE_CHART;
        }
        return super.getItemViewType(position);
    }

    /**
     * 初始化饼状图
     *
     * @param chart PieChart
     */
    private void initPieChart(PieChart chart) {
        chart.setDrawEntryLabels(true);
        //自动计算数据百分比
        chart.setUsePercentValues(true);
        chart.setDescription(null);
        chart.setTouchEnabled(false);
        chart.setEntryLabelTextSize(10f);
        chart.animateXY(1500, 1500);
        chart.setDrawEntryLabels(false);
        chart.setExtraOffsets(30.f, 0.f, 30.f, 0.f);
        chart.setHoleRadius(60f);
        chart.setTransparentCircleRadius(61f);
        //取消图表说明设置
        Legend l = chart.getLegend();
        l.setEnabled(false);
    }

    /**
     * 得到饼状图数据
     *
     * @param position 位置
     * @return         PieData
     */
    private PieData getPieData(int position) {
        List<PieEntry> pieEntries = new ArrayList<>();
        List<QuestionnaireDetail.StatisticalBean> statisticalBeanList = list.get(position).getStatistical();
        float sum = 0;
        for (int i = 0; i < statisticalBeanList.size(); i++) {
            sum += statisticalBeanList.get(i).getStisNum();
        }
        for (int i = 0; i < statisticalBeanList.size(); i++) {
            if (statisticalBeanList.get(i).getStisNum() != 0) {
                float percent = statisticalBeanList.get(i).getStisNum() / sum * 100;
                pieEntries.add(new PieEntry(percent, statisticalBeanList.get(i).getOptionsDescribe()));
            }

        }

        PieDataSet dataSet = new PieDataSet(pieEntries, list.get(position).getQuestionState());
        dataSet.setValueFormatter(new PercentFormatter());
        dataSet.setValueTextSize(14f);
        dataSet.setValueTextColor(Color.BLACK);
        dataSet.setColors(ColorConstants.CHART_COLORS);
        //设置线条
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);
        dataSet.setValueLinePart1OffsetPercentage(60.f);
        dataSet.setValueLinePart1Length(0.2f);
        dataSet.setValueLinePart2Length(0.6f);
        dataSet.setValueLineColor(Color.parseColor("#999999"));
        //dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        return new PieData(dataSet);
    }

    /**
     * 初始化条形图
     *
     * @param chart    BarChart
     * @param position  position
     */
    private void initBarChart(BarChart chart, int position ) {
        chart.setDescription(null);
        //设置拦截所有触摸事件
        chart.setTouchEnabled(false);

        XAxis xAxis = chart.getXAxis();
        xAxis.setDrawGridLines(false);
        xAxis.setLabelCount(5);
        xAxis.setTextSize(10f);
        //X轴Value设计
//        xAxis.setValueFormatter(valueFormatter);
        xAxis.setGranularity(1);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //去掉X轴数字显示
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return StringConstants.STRING_EMPTY;
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });
        //Y轴左侧
        YAxis yl = chart.getAxisLeft();
        yl.setDrawAxisLine(true);
        yl.setDrawGridLines(false);
        yl.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        //Y轴右侧
        YAxis yr = chart.getAxisRight();
        yr.setDrawAxisLine(true);
        yr.setDrawGridLines(false);
        yr.setAxisMinimum(0f);
        yr.setEnabled(false);
        chart.animateY(1500);
        //是否需要显示百分比
        DecimalFormat format = new DecimalFormat("###,###,##0");
        if (list.get(position).getStatistical().get(0).getStisNum() < 1) {
            yl.setValueFormatter(new PercentFormatter(format));
        } else {
            yl.setValueFormatter(new DefaultAxisValueFormatter(0));
        }
        //取消图表说明设置
        Legend l = chart.getLegend();
        l.setEnabled(false);
    }

    /**
     * 得到BarChart的data
     *
     * @param position 位置
     * @return         BarData
     */
    private BarData getBarData(int position) {
        List<BarEntry> barEntries = new ArrayList<>();
        List<QuestionnaireDetail.StatisticalBean> statisticalBeanList = list.get(position).getStatistical();
        //是否需要百分比显示value
        if (statisticalBeanList.get(0).getStisNum() < 1) {
            for (int i = 0; i < statisticalBeanList.size(); i++) {
                barEntries.add(new BarEntry(i + 1, statisticalBeanList.get(i).getStisNum()*100));
            }
            BarDataSet dataSet = new BarDataSet(barEntries, list.get(position).getQuestionState());
            dataSet.setColors(ColorConstants.CHART_COLORS);
            dataSet.setValueFormatter(new PercentFormatter());
            BarData barData = new BarData(dataSet);
            barData.setBarWidth(0.3f);
            barData.setValueTextSize(9);
            return barData;
        } else {
            for (int i = 0; i < statisticalBeanList.size(); i++) {
                barEntries.add(new BarEntry(i + 1, statisticalBeanList.get(i).getStisNum()));
            }
            BarDataSet dataSet = new BarDataSet(barEntries, list.get(position).getQuestionState());
            dataSet.setColors(ColorConstants.CHART_COLORS);
            BarData barData = new BarData(dataSet);
            barData.setBarWidth(0.3f);
            barData.setValueTextSize(8);
            return barData;
        }

    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    class BarChartViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.questionnaire_title_tv)
        TextView questionnaireTitleTv;
        @Bind(R.id.questionnaire_chart_bc)
        BarChart questionnaireChartBc;
        @Bind(R.id.option_list_rv)
        RecyclerView optionListRv;

        private ChartOptionListAdapter adapter;

        BarChartViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            adapter = new ChartOptionListAdapter();
            optionListRv.setLayoutManager(new LinearLayoutManager(context));
            optionListRv.setAdapter(adapter);
        }
    }

    class PieChartViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.questionnaire_title_tv)
        TextView questionnaireTitleTv;
        @Bind(R.id.questionnaire_chart_pc)
        PieChart questionnaireChartPc;
        @Bind(R.id.option_list_rv)
        RecyclerView optionListRv;

        private ChartOptionListAdapter adapter;

        PieChartViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            adapter = new ChartOptionListAdapter();
            optionListRv.setLayoutManager(new LinearLayoutManager(context));
            optionListRv.setAdapter(adapter);
        }
    }
}
